<!-- 绘制控制 -->
<template>
  <div class="layer-control">
    <div v-if="!previewMode" class="style-name">
      <!-- <a-button @click.stop="drewLine">
        绘制线
      </a-button>
      <a-button style="margin-left: 20px" @click="simpleSelect">
        简单选择
      </a-button>
      <a-button style="margin-left: 20px" @click="drewPoint">
        绘制点
      </a-button> -->
      <a-button style="margin-left: 15px" @click="drewPolygon">
        <form-outlined />
        绘制房间
      </a-button>
      <a-button style="margin-left: 30px" @click="drewLinen">
        <edit-outlined />
        绘制墙
      </a-button>
      <!-- <a-button style="margin-left: 10px" @click="simpleSelect">
        <delete-outlined />
        删除
      </a-button> -->
    </div>
    <a-divider v-if="submit && !previewMode" />
    <div v-if="submit" class="style-name">
      <a-button style="margin-left: 15px" @click="threePreviewClick">
        <export-outlined v-if="previewMode" />
        <file-search-outlined v-else />
        {{ previewMode? '退出预览' : '三维预览' }}
      </a-button>
      <a-button style="margin-left: 30px" @click="exportJsonFile">
        <cloud-upload-outlined />
        提&nbsp;&nbsp;&nbsp;&nbsp;交
      </a-button>
    </div>
    <a-divider v-if="property" />
    <div v-if="property" class="style-name">
      <a-form layout="horizontal" :model="formState" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="名&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;称">
          <a-input v-model:value="formState.name" placeholder="请输入名称" />
        </a-form-item>
        <a-form-item label="自定义ID">
          <a-input v-model:value="formState.id" disabled placeholder="自动生成" />
        </a-form-item>
        <a-form-item :label="isDrawWall ? '墙的颜色' : '房间颜色'">
          <ColorSelect ref="colorSelectRef" v-model="formState.color" />
        </a-form-item>
        <a-form-item :label="isDrawWall ? '墙的高度' : '房间高度'">
          <!-- <a-input v-model:value="formState.height" suffix="米" /> -->
          <a-input-number class="number-input-style" v-model:value="formState.height" :min="0" />
          <span class="unit-style">米</span>
        </a-form-item>
        <a-form-item v-if="isDrawWall" label="墙的宽度">
          <!-- <a-input v-model:value="formState.wallWidth" suffix="米" /> -->
          <a-input-number class="number-input-style" v-model:value="formState.wallWidth" :min="0" />
          <span class="unit-style">米</span>
        </a-form-item>
      </a-form>
    </div>
  </div>
  <ThreePreview ref="threePreviewRef" />
  <RightMenu
    ref="rightMenuRef"
    @roomsMerging="roomsMerging"
    @delectSelectFeatures="delectDrew"
    @fillMerging="fillMerging"
    @roomSplit="roomSplit"
    @wallSplit="wallSplit"
    @viewProperties="viewProperties"
    @featureScale="featureScale"
    @featureRotate="featureRotate"/>

  <a-modal v-model:visible="visibleProperty" title="元素属性" @ok="handleOk" :footer="null">
    <p class="feature-p"><span class="feature-property">名称：</span>{{formState.name}}</p>
    <p class="feature-p"><span class="feature-property">ID：</span>{{formState.id}}</p>
    <p class="feature-p"><span class="feature-property">颜色：</span>{{formState.color}}</p>
    <p class="feature-p"><span class="feature-property">高度：</span>{{formState.height}}米</p>
    <p v-if="isDrawWall" class="feature-p"><span class="feature-property">宽度：</span>{{formState.wallWidth}}米</p>
    <a-button style="margin-left: 200px; margin-top: 10px;" type="primary" @click="handleOk">确定</a-button>
  </a-modal>

  <OperationTips ref="operationTipsRef" />

</template>

<script setup>
import {
  reactive,
  onMounted,
  getCurrentInstance,
  ref,
  nextTick
} from 'vue'
import {
  FormOutlined,
  EditOutlined,
  DeleteOutlined,
  CloudUploadOutlined,
  FileSearchOutlined,
  ExportOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { exportJson, removeListByValue } from '../../utils/xingutils.js'
import MapboxDraw from '../../../public/lib/mapbox-draw/mapbox-gl-draw'
import StaticMode from '../../../public/lib/mapbox-draw/mapbox-gl-draw-static-mode'
import { SRMode, SRCenter } from '../../../public/lib/mapbox-draw/mapbox-gl-draw-scale-rotate-mode'
import ColorSelect from '../../components/ColorSelect.vue'
import RightMenu from '../../components/RightMenu.vue'
import ThreePreview from './ThreePreview.vue'
import OperationTips from './OperationTips.vue'
import { polygonsUnion, polygonSplit, lineSplit } from './polygontool.js'

// 组件声明
const colorSelectRef = ref(null)
const threePreviewRef = ref(null)
const rightMenuRef = ref(null)
const operationTipsRef = ref(null)

// 双向绑定变量声明
const property = ref(false)
const submit = ref(false)
const isDrawWall = ref(false)
const visibleProperty = ref(false)
const previewMode = ref(false)
const formState = reactive({
  name: '',
  id: '',
  color: '#ea9999',
  height: 0.4,
  wallWidth: 0.2
})

const { proxy } = getCurrentInstance()
const map = proxy.$root.$map
const config = proxy.$root.$mapconfig,
  path = import.meta.env.VITE_APP_PATH

// 编辑图层
const editLayer = ['editDrawFeature', 'editDrawFeaturesLine']
// 线要素集合
const lineFeatureList = []
// 面要素集合
const polygonFeatureList = []

let draw

onMounted(() => {
  initMapboxDraw()
  initDrawLayer()
})

// 初试化绘制插件
const initMapboxDraw = () => {
  // 修改绘制时的样式
  const drawOptions2 = {
    // 关闭自带的绘制按钮
    displayControlsDefault: false,
    styles: [
      {
        'id': 'highlight-active-points',
        'type': 'circle',
        'filter': ['all',
          ['==', '$type', 'Point'],
          ['==', 'meta', 'feature'],
          ['==', 'active', 'true']],
        'paint': {
          'circle-radius': 7,
          'circle-color': '#000000'
        }
      },
      {
        'id': 'points-are-blue',
        'type': 'circle',
        'filter': ['all',
          ['==', '$type', 'Point'],
          ['==', 'meta', 'feature'],
          ['==', 'active', 'false']],
        'paint': {
          'circle-radius': 5,
          'circle-color': '#000088'
        }
      },
      {
        'id': 'gl-draw-line',
        'type': 'line',
        'filter': ['all', ['==', '$type', 'LineString'], ['!=', 'mode', 'static']],
        'layout': {
          'line-cap': 'round',
          'line-join': 'round'
        },
        'paint': {
          'line-color': '#D20C0C',
          'line-dasharray': [0.2, 2],
          'line-width': 2
        }
      },
      // polygon fill
      {
        'id': 'gl-draw-polygon-fill',
        'type': 'fill',
        'filter': ['all', ['==', '$type', 'Polygon'], ['!=', 'mode', 'direct_select']],
        'paint': {
          'fill-color': '#D20C0C',
          'fill-outline-color': '#D20C0C',
          'fill-opacity': 0.1
        }
      },
      // polygon mid points
      {
        'id': 'gl-draw-polygon-midpoint',
        'type': 'circle',
        'filter': ['all',
          ['==', '$type', 'Point'],
          ['==', 'meta', 'midpoint']],
        'paint': {
          'circle-radius': 3,
          'circle-color': '#fbb03b'
        }
      },
      // polygon outline
      {
        'id': 'gl-draw-polygon-stroke-static',
        'type': 'line',
        'filter': ['all', ['==', '$type', 'Polygon'], ['==', 'mode', 'direct_select']],
        'layout': {
          'line-cap': 'round',
          'line-join': 'round'
        },
        'paint': {
          'line-color': '#000',
          'line-width': 3
        }
      },
      // 多边形轮廓描边
      // This doesn't style the first edge of the polygon, which uses the line stroke styling instead
      {
        'id': 'gl-draw-polygon-stroke-active',
        'type': 'line',
        'filter': ['all', ['==', '$type', 'Polygon'], ['!=', 'mode', 'simple_select']],
        'layout': {
          'line-cap': 'round',
          'line-join': 'round'
        },
        'paint': {
          'line-color': '#D20C0C',
          'line-dasharray': [0.2, 2],
          'line-width': 2
        }
      },
      // vertex point halos
      {
        'id': 'gl-draw-polygon-and-line-vertex-halo-active',
        'type': 'circle',
        'filter': ['all', ['==', 'meta', 'vertex'], ['==', '$type', 'Point'], ['!=', 'mode', 'static']],
        'paint': {
          'circle-radius': 5,
          'circle-color': '#FFF'
        }
      },
      // vertex points
      {
        'id': 'gl-draw-polygon-and-line-vertex-active',
        'type': 'circle',
        'filter': ['all', ['==', 'meta', 'vertex'], ['==', '$type', 'Point'], ['!=', 'mode', 'static']],
        'paint': {
          'circle-radius': 3,
          'circle-color': '#D20C0C'
        }
      },

      // INACTIVE (static, already drawn)
      // line stroke
      {
        'id': 'gl-draw-line-static',
        'type': 'line',
        'filter': ['all', ['==', '$type', 'LineString'], ['==', 'mode', 'static']],
        'layout': {
          'line-cap': 'round',
          'line-join': 'round'
        },
        'paint': {
          'line-color': '#000',
          'line-width': 3
        }
      },
      // polygon fill
      {
        'id': 'gl-draw-polygon-fill-static',
        'type': 'fill',
        'filter': ['all', ['==', '$type', 'Polygon'], ['==', 'mode', 'static']],
        'paint': {
          'fill-color': '#000',
          'fill-outline-color': '#000',
          'fill-opacity': 0.1
        }
      }
    ]
  }

  // 注册 ‘static’模式
  const modes = MapboxDraw.modes
  modes.static = StaticMode

  // 注册 旋转缩放 模式
  modes.scaleRotateMode = SRMode
  const drawOptions = {
    // 关闭自带的绘制按钮
    displayControlsDefault: false,
    modes: modes
  }
  draw = new MapboxDraw(drawOptions)
  map.addControl(draw)
  // console.log('draw=========>', draw)

  map.on('draw.selectionchange', selectionchange1)
  map.on('draw.update', update1)
}

// 初始化绘制的各种图层
const initDrawLayer = () => {
  const drawFeatureCollection = { 'type': 'FeatureCollection', 'features': [] }

  map.addSource('editDrawFeature', { 'type': 'geojson', 'data': drawFeatureCollection })
  //面层选中后的样式
  map.addLayer({
    id: 'editDrawFeature',
    type: 'fill',
    source: 'editDrawFeature',
    paint: {
      'fill-color': 'blue',
      'fill-opacity': 0.2 // 透明度
    },
    filter: ['in', '$type', 'Polygon']
  })
  //面层的线-选中样式
  map.addLayer({
    id: 'editDrawFeaturesLine',
    type: 'line',
    source: 'editDrawFeature',
    layout: {
      'line-cap': 'round',
      'line-join': 'round'
    },
    paint: {
      'line-color': '#ff0000',
      'line-width': 2
    },
    filter: ['in', '$type', 'Polygon']
  })
  mapAddEventListener()
}

// 为地图注册监听事件
const mapAddEventListener = () => {
  // map.on('click', mapClick)
  map.on('mousedown', onDrawMousedown)
  map.on('mouseup', onDrawMouseup)
  // 注册键盘监听事件
  document.onkeydown = onDrawKeydown
}

// 地图取消监听事件
const mapRemoveEventListener = () => {
  // map.off('click', mapClick)
  map.off('mousedown', onDrawMousedown)
  map.off('mouseup', onDrawMouseup)
}
const mp = {} // 鼠标位置mousePosition 用来判断鼠标是直接点击，还是拖动
// 鼠标按下事件
const onDrawMousedown = (e) => {
  // console.log('鼠标按下', e)
  mp.x1 = e.originalEvent.clientX
  mp.y1 = e.originalEvent.clientY
  rightMenuRef.value.hide()
}
// 菜单位置
const menuPosition = {
  top: '100px',
  left: '100px'
}
// 鼠标抬起事件
const onDrawMouseup = (e) => {
  // console.log('鼠标抬起', e)
  mp.x2 = e.originalEvent.clientX
  mp.y2 = e.originalEvent.clientY
  e.originalEvent.stopPropagation()
  // 鼠标拖动不监听，右击再监听
  if (isdrag(mp.x1, mp.y1, mp.x2, mp.y2) && e.originalEvent.button === 2) {
    const selectFeatures = draw.getSelected()
    // console.log(selectFeatures, selectFeatures)
    if(selectFeatures.features.length) {
      // 显示操作菜单--并判读显示菜单格式
      if (selectFeatures.features[0].geometry.type === 'Polygon') {
        rightMenuRef.value.show(selectFeatures.features.length > 1 ? 2 : 1)
      } else{
        rightMenuRef.value.show(selectFeatures.features.length > 1 ? 4 : 3)
      }

      // dom渲染完成后设置位置
      nextTick(() => {
        // 页面宽
        const clientWidth = document.documentElement.clientWidth
        // 页面高
        const clientHeight = document.documentElement.clientHeight
        // 菜单宽
        const menuWidth = rightMenuRef.value.$el.offsetWidth
        // 菜单高
        const menuHeight = rightMenuRef.value.$el.offsetHeight
        // 鼠标x
        const eventX = e.originalEvent.pageX
        // 鼠标y
        const eventY = e.originalEvent.pageY

        // 菜单边界判断
        if(clientHeight - eventY >= menuHeight) {
          menuPosition.top = eventY + 'px'
        }else{
          menuPosition.top = eventY - menuHeight + 'px'
        }
        if(clientWidth - eventX >= menuWidth) {
          menuPosition.left = eventX + 'px'
        }else{
          menuPosition.left = eventX - menuWidth + 'px'
        }
        // 设置菜单位置
        rightMenuRef.value.setPosition(menuPosition)
      })

    }else {
      message.warn('请先选中图形')
    }
  }
}

// 判断鼠标是拖动还是点击
const isdrag = (x1, y1, x2, y2) =>  {
  if (Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) <= 5) {
    return true
  }
  return false
}

// 键盘抬起监听事件 --- 主要监听绘制时的Esc键
const onDrawKeydown = (e) => {
  // console.log(e)
  // 在绘制模式时候，Esc键退出，修改操作提示，关闭信息框
  const drawMode = draw.getMode()
  // console.log('drawMode', drawMode)
  if(e.keyCode === 27) {
    if(drawMode === 'draw_line_string' || drawMode === 'draw_polygon') {
      operationTipsRef.value.changeTips(1)
      property.value = false
    }
  }
}

// 自定义绘制线
const drewLine = () => {
  // console.log('绘制线')
  map.getCanvas().style.cursor = 'crosshair'
  // 禁止双击缩放
  map.doubleClickZoom.disable()
  let isMeasure = true
  const jsonPoint = {
    'type': 'FeatureCollection',
    'features': []
  }
  const jsonLine = {
    'type': 'FeatureCollection',
    'features': []
  }
  const source = map.getSource('points')
  const lineMoveSource = map.getSource('line-move')
  const lineSource = map.getSource('line')

  if(source) {
    map.getSource('points').setData(jsonPoint)
    if(lineMoveSource) {
      map.getSource('line-move').setData(jsonLine)
    }
    if(lineSource) {
      map.getSource('line').setData(jsonLine)
    }
  } else {
    map.addSource('points', {
      type: 'geojson',
      data: jsonPoint
    })
    map.addSource('line', {
      type: 'geojson',
      data: jsonLine
    })
    map.addSource('line-move', {
      type: 'geojson',
      data: jsonLine
    })
    map.addLayer({
      id: 'line-move',
      type: 'line',
      source: 'line-move',
      paint: {
        'line-color': '#ff0000',
        'line-width': 10,
        'line-opacity': 0.65
      }
    })
    map.addLayer({
      id: 'line',
      type: 'line',
      source: 'line',
      paint: {
        'line-color': '#ff0000',
        'line-width': 10,
        'line-opacity': 0.65
      }
    })
    map.addLayer({
      id: 'points',
      type: 'circle',
      source: 'points',
      paint: {
        'circle-color': '#ffffff',
        'circle-radius': 5,
        'circle-stroke-width': 10,
        'circle-stroke-color': '#ff0000'
      }
    })

    function addPoint(coords) {
      if(jsonPoint.features.length > 0) {
        const prev = jsonPoint.features[jsonPoint.features.length - 1]

        jsonLine.features.push({
          type: 'Feature',
          geometry: {
            type: 'LineString',
            coordinates: [prev.geometry.coordinates, coords]
          }
        })
        map.getSource('line').setData(jsonLine)
      }
      jsonPoint.features.push({
        type: 'Feature',
        geometry: {
          type: 'Point',
          coordinates: coords
        }
      })
      map.getSource('points').setData(jsonPoint)
    }
    map.on('click', function (_e) {
      if(isMeasure) {
        const coords = [_e.lngLat.lng, _e.lngLat.lat]

        addPoint(coords)
        //points.push(coords);
      }
    })
    map.on('mousemove', function (_e) {
      if(isMeasure) {
        const coords = [_e.lngLat.lng, _e.lngLat.lat]

        if (jsonPoint.features.length > 0) {
          const prev = jsonPoint.features[jsonPoint.features.length - 1]

          const json = {
            type: 'Feature',
            geometry: {
              type: 'LineString',
              coordinates: [prev.geometry.coordinates, coords]
            }
          }

          map.getSource('line-move').setData(json)

        }
      }
    })
    map.on('dblclick', function (_e) {
      if(isMeasure) {
        const coords = [_e.lngLat.lng, _e.lngLat.lat]

        addPoint(coords)
        isMeasure = false
        map.getCanvas().style.cursor = 'grab'
        // jsonPoint.features = [];
        // jsonLine.features = [];
      }
    })
  }
}
// 取消选中
const simpleSelect = () => {
  // draw.changeMode('simple_select')
  // console.log(draw.getMode())
  // draw.changeMode('splitLineMode', { spliter: 'line_string' })
}
// 插件--绘制点
const drewPoint = () => {
  viewSetVertical(0)
  draw.changeMode('draw_point')
}
// 插件--绘制线
const drewLinen = () => {
  isDrawWall.value = true
  property.value = true
  viewSetVertical(0)
  operationTipsRef.value.changeTips(2)
  draw.changeMode('draw_line_string')
  message.info('请在地图上绘制墙线，并填写对应属性信息！')
}
// 插件--绘制面
const drewPolygon = () => {
  isDrawWall.value = false
  property.value = true
  viewSetVertical(0)
  operationTipsRef.value.changeTips(2)
  draw.changeMode('draw_polygon')
  message.info('请在地图上绘制房间面，并填写对应属性信息！')
}
// 删除选中要素
const delectDrew = () => {
  // console.log('删除选中面', lineFeatureList, polygonFeatureList)
  // 停止正在的编辑
  const idlist = draw.getSelectedIds()
  if(idlist.length) {
    draw.delete(idlist)
    for (const idstring of idlist) {
      // 根据id删除数组中数据
      removeListByValue(lineFeatureList, 'id', idstring)
      removeListByValue(polygonFeatureList, 'id', idstring)
    }
    // 关闭属性框 重新判断所剩数据
    property.value = false
    resetForm()
    // 取消选中时判断是否展示三维展示和提交按钮
    judgeData()
    message.success('删除成功。')
    operationTipsRef.value.changeTips(1)
  }else{
    message.warning('当前还未选中要删除的要素，请选中后删除！！！')
  }

}
// 视角设置垂直
const viewSetVertical = (pitchNum) => {
  const {lng, lat} = map.getCenter()

  map.flyTo({
    center: [lng, lat],
    pitch: pitchNum
  })
}

let saveSelectObj

// 选中图形后
const selectionchange1 = () => {
  const data = draw.getSelected()

  // console.log('选中的图形数据======》', data)
  // 选中多个，关闭属性框
  if(data.features.length > 1) {
    property.value = false
  } else if(data.features.length === 1) {  // 选中1个绑定属性
    const feature = data.features[0]

    // 开启补面合并开关后的绘制面完成后操作
    if(fillMergingSwitch) {
      fillMergingSelectFeatures.push(feature)
      fillMergingDraw()
      return
    }
    // 开启房间分割绘制线结束后操作
    if(roomSplitSwitch) {
      roomSplitDraw(feature)
      return
    }
    // 开启墙体分割绘制线结束后操作
    if(wallSplitSwitch) {
      wallSplitDraw(feature)
      return
    }
    saveSelectObj = data
    // 根据选中类型判断是否是墙
    if(feature.geometry.type === 'Polygon') {
      isDrawWall.value = false
    }else if(feature.geometry.type === 'LineString') {
      isDrawWall.value = true
    }
    // 选中时展示属性栏
    property.value = true

    // console.log('选中feature=====>', feature)

    //判断要素类型 - 把要素和属性添加到表单中-，等dom渲染完成在进行属性设置
    nextTick(() => {
      if(feature.geometry.type === 'Polygon') {
        showProperties(polygonFeatureList, feature)
      }else if(feature.geometry.type === 'LineString') {
        showProperties(lineFeatureList, feature)
      }
    })

  } else if(data.features.length === 0) { // 取消选中

    // 其他事件误触发的取消选中事件判断
    if (selecteSwitch === true) {
      selecteSwitch = false
      return
    }
    const feature = saveSelectObj.features[0]
    // console.log('取消选中feature=====>', saveSelectObj)
    //判断要素类型 - 把要素和属性添加到数组中
    if(feature.geometry.type === 'Polygon') {
      listAddFeature(polygonFeatureList, feature)
    }else if(feature.geometry.type === 'LineString') {
      listAddFeature(lineFeatureList, feature)
    }
    // 取消选中改变提示
    if(!fillMergingSwitch && !roomSplitSwitch && !wallSplitSwitch) {
      operationTipsRef.value.changeTips(1)
    }
    // 取消选中时判断是否展示三维展示和提交按钮
    judgeData()
    // 取消选中取消属性栏--且回复属性栏默认值
    property.value = false
    resetForm()
  }
}
// 向数组中添加要素
const listAddFeature = (list, fea) => {
  const isexist = list.some((f) => {
    if(f.id === fea.id) {
      f.properties = {...formState}
      f.geometry = fea.geometry
      return true
    }
  })
  // 没有就新增
  if(!isexist) {
    list.push({
      id: fea.id,
      geometry: fea.geometry,
      properties: {...formState},
      type: fea.type
    })
  }
}

// 查找数组中是否应添加该属性
const showProperties = (list, fea) => {
  list.some((f) => {
    if(f.id === fea.id) {
      formState.name = f.properties.name
      formState.id = f.id
      formState.color = f.properties.color
      formState.height = f.properties.height
      formState.wallWidth = f.properties.wallWidth
      // console.log('formState', formState, colorSelectRef)
      colorSelectRef.value.changeColor(f.properties.color)
      return true
    }
  })
}
// 判断数据是否还有展示提交按钮
const judgeData = () => {
  if(polygonFeatureList.length > 0 || lineFeatureList.length > 0) {
    submit.value = true
  }else{
    submit.value = false
  }
}
// 属性栏恢复默认值
const resetForm = () => {
  formState.name = ''
  formState.id = ''
  formState.color = '#ea9999'
  formState.height = 0.4
  formState.wallWidth = 0.2
  colorSelectRef.value?.changeColor('#ea9999')
}
// 图形更新
const update1 = (e) => {
  // console.log('图形更新', e)
  saveSelectObj = e
  const feature = e.features[0]
  // 更新图形数据
  if(feature.geometry.type === 'Polygon') {
    listAddFeature(polygonFeatureList, feature)
  }else if(feature.geometry.type === 'LineString') {
    listAddFeature(lineFeatureList, feature)
  }
}
// 地图点击事件
const mapClick = (e) => {
  // if (draw.model === undefined || draw.model === null) {}
  // e.lngLat = map.catch.lngLat(e);//捕捉(如果开启了则调用，未开启则不调用)
  // const features = map.queryRenderedFeatures([[e.point.x - 5, e.point.y - 5], [e.point.x + 5, e.point.y + 5]], { layers: editLayer })

  // console.log('features',features)

  // const selectId = draw.add(features[0].geometry)
  // console.log(e)

}
// 导出模型调整位置后的配置文件
const exportJsonFile = () => {
  const exportData = {
    type: 'FeatureCollection',
    features:[...polygonFeatureList, ...lineFeatureList]
  }
  exportJson(exportData, '房间数据.json')
  // draw.set({
  //   type: 'FeatureCollection',
  //   features:[...polygonFeatureList, ...lineFeatureList]
  // })
}
// 三维预览
const threePreviewClick = () => {
  if(previewMode.value) { // 要退出三维预览模式进入编辑模式
    // console.log('退出三维预览模式')
    operationTipsRef.value.changeTips(1)
    threePreviewRef.value.removeLayer()
    viewSetVertical(0)
    draw.set({
      type: 'FeatureCollection',
      features:[...polygonFeatureList, ...lineFeatureList]
    })
  }else{ // 进入三维预览模式
    operationTipsRef.value.changeTips(7)
    // 退出选中状态
    draw.changeMode('static')
    draw.changeMode('simple_select')
    // 删除全部
    draw.deleteAll()
    // 视角倾斜
    viewSetVertical(70)
    setTimeout(() => {
      threePreviewRef.value.loadShowLayer(polygonFeatureList, lineFeatureList)
    }, 100)
  }
  previewMode.value = !previewMode.value

}
// 房间合并
const roomsMerging  = () => {
  const selectFeatures = draw.getSelected()
  const unionPolygon = polygonsUnion(selectFeatures.features[0], selectFeatures.features)
  // console.log('unionPolygon===>', unionPolygon, selectFeatures)
  // unionPolygon.geometry.type:"Polygon" --- 合并成功   MultiPolygon---合并失败
  if(unionPolygon.geometry.type === 'Polygon') { // 合并成功
    // 新增合并后的面
    const unionPolygonId = draw.add(unionPolygon.geometry)[0]
    unionPolygon.id = unionPolygonId
    listAddFeature(polygonFeatureList, unionPolygon)
    // 删除选中的面
    for (const selFeature of selectFeatures.features) {
      draw.delete(selFeature.id)
      // 根据id删除数组中数据
      removeListByValue(polygonFeatureList, 'id', selFeature.id)
    }
    message.success('房间合并成功。')
  }else{ // unionPolygon.geometry.type === 'MultiPolygon' 合并失败
    message.error('合并失败，合并面需要有相交部分，否则请使用【补面合并】功能。', 10)
  }
}
let fillMergingSwitch = false // 补面合并的开关
let fillMergingSelectFeatures // 补面合并选中的
// 补面合并
const fillMerging  = () => {
  message.info('请绘制与需要合并面相交的面！')
  fillMergingSelectFeatures = draw.getSelected().features
  draw.changeMode('draw_polygon')
  fillMergingSwitch = true
  operationTipsRef.value.changeTips(6)
}
// 补面合并-绘制面后操作
const fillMergingDraw  = () => {
  fillMergingSwitch = false
  // 把选中的面和其他两个面合并，
  const unionPolygon = polygonsUnion(fillMergingSelectFeatures[0], fillMergingSelectFeatures)

  if(unionPolygon.geometry.type === 'Polygon') { // 合并成功
    // 删除选中的面
    for (const selFeature of fillMergingSelectFeatures) {
      draw.delete(selFeature.id)
      // 根据id删除数组中数据
      removeListByValue(polygonFeatureList, 'id', selFeature.id)
    }
    // 新增合并后的面
    const unionPolygonId = draw.add(unionPolygon.geometry)[0]
    unionPolygon.id = unionPolygonId
    listAddFeature(polygonFeatureList, unionPolygon)
    message.success('补面合并成功。')
  }else{ // unionPolygon.geometry.type === 'MultiPolygon' 合并失败
    draw.delete(draw.getSelectedIds())
    message.error('合并失败，绘制的面要与需要合并的面都相交', 10)
  }
  // 补面绘制完成后会触发第一个面的选中和取消选中事件---未找到原因
  selecteSwitch = true
  operationTipsRef.value.changeTips(1)
  draw.changeMode('direct_select')
}
let selecteSwitch = false // 绘制结束触发的选中和取消选中事件判断有用无用开关

let roomSplitSwitch = false // 房间分割的开关
let splitSelectFeature // 切割选中的面
// 房间分割
const roomSplit  = () => {
  message.info('请绘制分割线！')
  splitSelectFeature = draw.getSelected().features[0]
  draw.changeMode('draw_line_string')
  roomSplitSwitch = true
  operationTipsRef.value.changeTips(3)
}

// 房间分割-绘制面后操作
const roomSplitDraw = (lineFeature) => {
  // console.log(draw.getMode())
  roomSplitSwitch = false
  // 使用线要素进行分割
  const splitResult = polygonSplit(lineFeature, splitSelectFeature)

  // 删除绘制的线要素
  draw.delete(lineFeature.id)
  if(splitResult.success) { // 切割成功
    // 删除原面
    draw.delete(splitSelectFeature.id)
    removeListByValue(polygonFeatureList, 'id', splitSelectFeature.id)

    const splitResultid1 = draw.add(splitResult.polygons[0].geometry)[0]
    splitResult.polygons[0].id = splitResultid1
    const splitResultid2 = draw.add(splitResult.polygons[1].geometry)[0]
    splitResult.polygons[1].id = splitResultid2

    listAddFeature(polygonFeatureList, splitResult.polygons[0])
    listAddFeature(polygonFeatureList, splitResult.polygons[1])
    // console.log('polygonFeatureList', polygonFeatureList)
    message.success('房间分割成功。')
  } else {
    message.error('房间分割失败, ' + splitResult.message + ', 请重新绘制分割线', 10)
    setTimeout(() => {
      roomSplitSwitch = true
      draw.changeMode('draw_line_string')
    }, 500)
  }
  // 补面绘制完成后会触发第一个面的选中和取消选中事件---未找到原因
  selecteSwitch = true
  operationTipsRef.value.changeTips(1)
  draw.changeMode('direct_select')
}

let wallSplitSwitch = false // 墙体分割的开关
// 墙体分割
const wallSplit = () => {
  message.info('请绘制分割线！')
  splitSelectFeature = draw.getSelected().features[0]
  draw.changeMode('draw_line_string')
  wallSplitSwitch = true
  operationTipsRef.value.changeTips(8)
}
// 墙体分割-绘制面后操作
const wallSplitDraw = (lineFeature) => {
  // console.log(draw.getMode())
  wallSplitSwitch = false
  // 使用线要素进行分割
  const splitResult = lineSplit(lineFeature, splitSelectFeature)

  // 删除绘制的线要素
  draw.delete(lineFeature.id)
  if(splitResult.success) { // 切割成功
    // 删除原线
    draw.delete(splitSelectFeature.id)
    removeListByValue(lineFeatureList, 'id', splitSelectFeature.id)

    const splitResultid1 = draw.add(splitResult.lines[0].geometry)[0]
    splitResult.lines[0].id = splitResultid1
    const splitResultid2 = draw.add(splitResult.lines[1].geometry)[0]
    splitResult.lines[1].id = splitResultid2

    listAddFeature(lineFeatureList, splitResult.lines[0])
    listAddFeature(lineFeatureList, splitResult.lines[1])
    // console.log('lineFeatureList', lineFeatureList)
    message.success('墙体分割成功。')
  } else {
    message.error('墙体分割失败, ' + splitResult.message + ', 请重新绘制分割线', 10)
    setTimeout(() => {
      wallSplitSwitch = true
      draw.changeMode('draw_line_string')
    }, 500)
  }
  // 补面绘制完成后会触发第一个面的选中和取消选中事件---未找到原因
  selecteSwitch = true
  operationTipsRef.value.changeTips(1)
  draw.changeMode('direct_select')
}

// 旋转
const featureRotate = () => {
  operationTipsRef.value.changeTips(5)
  draw.changeMode('scaleRotateMode', {
    canScale: false,
    canRotate: true, // only rotation enabled
    canTrash: false, // disable feature delete

    rotatePivot: SRCenter.Center, // rotate around center
    // scaleCenter: SRCenter.Opposite, // scale around opposite vertex

    singleRotationPoint: true, // only one rotation point
    rotationPointRadius: 1.2, // offset rotation point

    canSelectFeatures: true
  })
}

// 缩放
const featureScale = () => {
  operationTipsRef.value.changeTips(4)
  draw.changeMode('scaleRotateMode', {
    canScale: true,
    canRotate: false, // only rotation enabled
    canTrash: false, // disable feature delete

    rotatePivot: SRCenter.Center, // rotate around center
    scaleCenter: SRCenter.Opposite, // scale around opposite vertex

    singleRotationPoint: true, // only one rotation point
    rotationPointRadius: 1.2, // offset rotation point

    canSelectFeatures: true
  })
}

// 查看属性
const viewProperties = () => {
  // 展示属性框
  visibleProperty.value = true
  // 获取选中要素属性信息
  // 把信息填写再属性框中
}
// 属性框关闭
const handleOk = () => {
  visibleProperty.value = false
}


</script>
<style lang='scss' scoped>
.layer-control {
  width: 335px;
  padding: 5px 0 24px 0;
  .style-name {
    display: inline-block;
    padding-left: 15px;
  }
  .number-input-style{
    width: 150px;
  }
  .unit-style{
    margin-left: 10px;
  }
}
.feature-p{
  margin-left: 28px;
  .feature-property{
    display: inline-block;
    min-width: 56px;
  }
}
</style>
